package sk.fiit.lulco.gui;

import java.io.IOException;

import sk.fiit.lulco.grafy.Graph;

public abstract class GraphThread implements Runnable {

	private boolean cancel;
	private GraphListener listener;
	private Settings settings;
	private GraphItem item;
	private Graph out;

	public GraphThread(GraphItem item) {
		this.item = item;
	}

	public GraphListener getListener() {
		return listener;
	}

	public void setListener(GraphListener listener) {
		this.listener = listener;
	}

	protected void fireOnGraphEvent(GraphEvent evt) {
		if (listener != null) {
			listener.onGraphEvent(evt);
		}
	}

	protected void fireOnFinish() {
		if (listener != null) {
			listener.onFinish();
		}
	}

	protected void fireOnTextAppend(String text) {
		if (listener != null) {
			listener.onTextAppend(text);
		}
	}

	protected void fireOnError(String message) {
		if (listener != null) {
			listener.onError(message);
		}
	}

	public Settings getSettings() {
		return settings;
	}

	public void setSettings(Settings settings) {
		this.settings = settings;
	}

	protected GraphItem getItem() {
		return item;
	}

	public Graph getOut() {
		return out;
	}

	protected void setOut(Graph out) {
		this.out = out;
	}

	private Graph init() throws IOException {
		Graph graph = new Graph(item.getFileName());
		graph.setWidth(item.getWidth());
		graph.setHeight(item.getHeight());
		
		return graph;
	}

	@Override
	public void run() {
		fireOnTextAppend("Initializinig");
		try {
			Graph graph = init();
			graph = runPerformed(graph);

			fireOnGraphEvent(new GraphEvent(graph, null, 0, 0, 0));
			fireOnTextAppend("Finished");
			fireOnFinish();
		} catch (Exception ex) {
			fireOnError("Error occured, reason: " + ex.getMessage());
			for (StackTraceElement element : ex.getStackTrace()) {
				fireOnError(element.toString());
			}
		}
	}

	public void cancel() {
		this.cancel = true;
	}
	
	protected boolean isCancelSet() {
		return cancel;
	}

	protected abstract Graph runPerformed(Graph graph);
}
